package org.example.algorithm.backtracking;

import java.util.ArrayList;
import java.util.List;

public class CombinationSumSolution {

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        if (candidates.length == 0) {
            return res;
        }
        List<Integer> list = new ArrayList<>();
        int index = 0;
        doCombinationSum(res, candidates, target, index, list);
        return res;
    }

    private void doCombinationSum(List<List<Integer>> res, int[] candidates, int target, int index, List<Integer> list) {
        if (0 == target) {
            res.add(new ArrayList<>(list));
        } else if(0 > target) {
            return;
        } else {
            for (int i=index;i<candidates.length;i++) {
                list.add(candidates[i]);
                doCombinationSum(res, candidates,target-candidates[i], i, list);
                list.remove(list.size()-1);
            }
        }
    }

    public static void main(String[] args) {
        int[] candidates = {2,3,6,7};
        int target = 7;
        CombinationSumSolution solution = new CombinationSumSolution();
        List<List<Integer>> res = solution.combinationSum(candidates, target);
        System.out.println(res);
    }
}
